package com.token.sysflow.core;
import com.token.base.Pl;
import com.token.sql.IntegrateSql;
import com.token.sysflow.bean.FSysFlowSubmitLog;
import com.token.sysflow.exception.FlowException;
import com.token.sysflow.impl.AbstractFlowHandlerImpl;


/**
 *
 * @author chenjianxiong 2020/4/13
 */
public class FlowHandlerService {
    private final IntegrateSql iSql;

    /**
     *
     * @param iSql
     */
    public FlowHandlerService(IntegrateSql iSql){
        this.iSql = iSql;

    }

    /**
     * 执行操作
     * @param handler
     * @return
     * @throws Exception
     */
    public boolean execute(AbstractFlowHandlerImpl handler)throws Exception{
        boolean isOk = false;
        try {
            handler.writeInJson();
            handler.initParameter(iSql);
            iSql.setAutoCommit(false);
            isOk = handler.submitHandler();
            handler.close();
            iSql.commit();
        } catch (FlowException e){ //逻辑错误
            iSql.rollback();
            handler.handleReturnErr(e);
            e.printStackTrace();
        } catch (Exception e){//代码错误
            iSql.rollback();
            handler.handleReturnErr(e);
            e.printStackTrace();
        }finally {
            createFlowSubmitLog(handler); //写日志
            iSql.commit();
        }

        return isOk;
    }

    /**
     *
     * @param handler
     */
    private void createFlowSubmitLog(AbstractFlowHandlerImpl handler){
        try {
            String json_in = handler.getInParamJson().toJSONString();
            String json_out = handler.getResult().toJSONString();
//            System.out.println("--->输入参数：" + json_in);
//            System.out.println("--->输出参数：" + json_out);
            FSysFlowSubmitLog log = new FSysFlowSubmitLog(iSql);
            log.setInsert();
            log.setSysId(handler.getSysId());
            log.setKeyUnid(handler.getKeyUnid()); //单据关联
            log.setActionType(handler.getActionType().getId()); //操作类型
            log.setActionText(handler.getActionType().getName());
            log.setActionStartTime(handler.getActionTimer()); //提交时间
            log.setActionUser(handler.getActionUser()); //提交人
            log.setInParameter(json_in); //输入参数
            log.setOutParameter(json_out); //输出参数
            log.setActionEndTime(Pl.getCurDataTime());
            log.setCode(handler.getResult().getIntValue("code"));
            log.setFlowNo(handler.getFlowNo());
            log.executeUpdate();
            log.close();

        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
